<?php

/**
 * question actions.
 *
 * @package    docplus.co.za
 * @subpackage question
 * @author     Fox Matuku
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class questionActions extends gfFrontendActions
{

    public function preExecute()
    {
        $this->getUser()->setCurrentRoute("question");
        parent::preExecute();
    }

    public function executeIndex(sfWebRequest $request)
    {
        $this->question = new Question();
        if ($this->getUser()->isAuthenticated())
        {
            $this->question->setUserId($this->getUser()->getDpUser()->getId());
        }

        $this->form = new QuestionForm($this->question);
    }

    public function executeShow(sfWebRequest $request)
    {
        $this->question = QuestionTable::getInstance()->findOneById($request->getParameter("id", null));

        $answerComment = new AnswerComment();
        if ($this->getUser()->isAuthenticated())
        {
            $answerComment->setUserId($this->getUser()->getDpUser()->getId());
        }
        $this->form = new AnswerCommentForm($answerComment);
    }

    public function executeRelated(sfWebRequest $request)
    {
        $this->question = QuestionTable::getInstance()->findOneById($request->getParameter("question_id", null));

        $answerComment = new AnswerComment();
        if ($this->getUser()->isAuthenticated())
        {
            $answerComment->setUserId($this->getUser()->getDpUser()->getId());
        }
        $this->form = new AnswerCommentForm($answerComment);
    }

    public function executeNew(sfWebRequest $request)
    {
        $this->question = new Question();
        if ($this->getUser()->isAuthenticated())
        {
            $this->question->setUserId($this->getUser()->getDpUser()->getId());
        }
        $this->form = new QuestionForm($this->question);

        if ($request->isMethod('post'))
        {
            $this->form->bind($request->getParameter($this->form->getName()));
            if ($this->form->isValid())
            {
                try
                {
                    $question = $this->form->save();
                    $user = $this->getUser()->getDpUser();
                    
                    // log this activity
                    $description = $this->getPartial('common/activity_log', array('question' => $question, 'type' => 'ask', 'user' => $user));
                    $this->dispatcher->notify(new sfEvent($this, 'activity.log', array('description' => $description, 'points' => 5, 'user' => $this->getUser()->getDpUser())));

                    $emailAddresses = sfConfig::get("app_email_question");
                    
                    $mailer = new gfMailer();
                    $mailer->setTemplate('question-confirmation');
                    $mailer->setToEmails($user->getName() . " <" . $user->getEmail() . ">");
                    $mailer->addValues(array(
                        "USER" => $this->getUser()->getDpUser(),
                        "QUESTION_URL" =>  $this->generateUrl("question_show", array("id" => $question->getId()), true),
                        "QUESTION" => $question->getEnquiry(),
                        "PREVIOUS_QUESTIONS_URL" => $this->generateUrl("related_questions", array("question_id" => $question->getId()), true)
                    ));
                    $mailer->send();

                    // send the asker the doctors response
                    $this->getUser()->setFlash('notice', 'Thanks for submitting your question. Please note that you will be automatically sent an email once our experts have answered your question :)');

                    $this->redirect("@question_new");
                }
                catch (Exception $e)
                {
                    throw $e;
                    // invoke the event here so we get the error via email
                }
            }
            else
            {
                $this->getUser()->setQuestionDetails($request->getParameter($this->form->getName()));

                if (!$this->getUser()->isAuthenticated())
                    die("signin");
            }
        }
    }

    public function executeAnonymous(sfWebRequest $request)
    {
        $this->question = new Question();
        if ($this->getUser()->isAuthenticated())
        {
            $this->question->setUserId($this->getUser()->getDpUser()->getId());
        }

        // make sure you prepolute the question form with the previously put in question
        $anonymousQuestionDetails = $this->getUser()->getQuestionDetails();

        $this->question->setEnquiry(isset($anonymousQuestionDetails['enquiry']) ? $anonymousQuestionDetails['enquiry'] : 'Ask a new question...');

        $this->form = new AnonymousQuestionForm($this->question);
        if ($request->isMethod('post'))
        {
            $this->form->bind($request->getParameter($this->form->getName()));
            if ($this->form->isValid())
            {
                try
                {
                    $email = $this->form->getValue("email");
                    $friendEmail = $this->form->getValue("friend_email");

                    $emails = array();
                    $emails[] = $email;

                    if ($friendEmail != "")
                    {
                        $emails[] = $friendEmail;
                    }

                    $user = GfUserTable::getInstance()->createAnonymousUserByEmails($emails);

                    $question = new Question();
                    $question->setUser($user);
                    $question->setEnquiry($this->form->getValue("enquiry"));
                    $question->save();

                    $description = $this->getPartial('common/activity_log', array('question' => $question, 'user' => $user, 'type' => 'ask'));
                    $this->dispatcher->notify(new sfEvent($this, 'activity.log', array('description' => $description, 'points' => 5, 'user' => $user)));

                    $mailer = new gfMailer();
                    $mailer->setTemplate('question-confirmation');
                    $mailer->setToEmails($user->getName() . " <" . $user->getEmail() . ">");
                    $mailer->addValues(array(
                        "USER" => $user,
                        "QUESTION_URL" => $this->generateUrl("question_show", array("id" => $question->getId()), true),
                        "QUESTION" => $question->getEnquiry(),
                        "PREVIOUS_QUESTIONS_URL" => $this->generateUrl("related_questions", array("question_id" => $question->getId()), true)
                    ));
                    $mailer->send();
                    
                    // clear the question off the session
                    $this->getUser()->setQuestionDetails(array());

                    // send the asker the doctors response
                    $this->getUser()->setFlash('notice', 'Thanks for submitting your question. Please note you will need to confirm your email address before we can share your question with hundreds of licensed RSA physicians :)');

                    $this->redirect("@question_anonymous");
                }
                catch (Exception $e)
                {
                    throw $e;
                    // invoke the event here so we get the error via email
                }
            }
            else{
                $this->getUser()->setQuestionDetails($request->getParameter($this->form->getName()));
            }
        }
    }

}
